package com.cxs.controller;

import com.cxs.entity.dto.AdminAddRoomDTO;
import com.cxs.enums.OpenTypeEnum;
import com.cxs.entity.Admin;
import com.cxs.entity.Classroom;
import com.cxs.entity.Seat;
import com.cxs.service.AdminService;
import com.cxs.service.ClassroomService;
import com.cxs.service.SeatOrderService;
import com.cxs.service.SeatService;
import com.cxs.entity.vo.AdminLoginVO;
import com.cxs.entity.vo.ClassroomVO;
import com.cxs.entity.vo.Result;
import com.cxs.entity.vo.SeatOrderVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: AdminController
 * @description:
 * @author: 诗涵
 * @create: 2024-01-07 08:17
 */
@Controller
@RequestMapping("/admin")
@RequiredArgsConstructor
public class AdminController {
    private final AdminService adminService;
    private final ClassroomService classroomService;
    private final SeatService seatService;
    private final SeatOrderService seatOrderService;


    @RequestMapping("/")
    public String toIndex(HttpSession session, Model model) {
        Object user = session.getAttribute("loginUser");
        if (null != user) {
            if (user instanceof AdminLoginVO) {
                AdminLoginVO loginVO = (AdminLoginVO) user;
                model.addAttribute("user", loginVO);
                return "admin/index";
            }else {
                return "redirect:/auth/login";
            }
        } else {
            return "redirect:/auth/login";
        }
    }

    @RequestMapping("/toAdminList")
    public String toAdminList(Model model) {
        List<Admin> list = adminService.list(null);
        model.addAttribute("adminList", list);
        return "admin/adminList";
    }

    @RequestMapping("/toEditAdmin")
    public String toEditAdmin(@RequestParam("id") Integer id, Model model) {
        Admin admin = adminService.getById(id);
        model.addAttribute("editUser", admin);
        return "admin/editAdmin";
    }

    @RequestMapping("/deleteAdmin")
    public String deleteAdmin(@RequestParam("id") Integer id,Model model) {
        adminService.removeById(id);
        List<Admin> list = adminService.list(null);
        model.addAttribute("adminList", list);
        return "admin/adminList";
    }

    @RequestMapping("/toAddAdmin")
    public String toAddAdmin(Model model) {
        return "admin/addAdmin";
    }

    @RequestMapping("/toEditRoom")
    public String toEditRoom(@RequestParam("id") Integer id,Model model) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
        Classroom classroom = classroomService.getById(id);
        ClassroomVO vo = new ClassroomVO();
        BeanUtils.copyProperties(classroom, vo);
        vo.setOpenTimeEndStr(formatter.format(classroom.getOpenTimeEnd()));
        vo.setOpenTimeStartStr(formatter.format(classroom.getOpenTimeStart()));
        vo.setOpenTimeRange(vo.getOpenTimeStartStr() + "-" + vo.getOpenTimeEndStr());
        vo.setOpenDesc(OpenTypeEnum.getDesc(classroom.getOpenType()));
        model.addAttribute("room", vo);
        return "admin/editRoom";
    }

    @RequestMapping("/updateAdmin")
    @ResponseBody
    public Map<String, Object> updateAdmin(Admin admin, Model model) {
        Map<String, Object> res = new HashMap<>();
        res.put("code", 200);
        res.put("msg", "操作成功");
        boolean b = adminService.updateById(admin);
        if (!b) {
            res.put("code", -1);
            res.put("msg", "操作失败");
        }
        return res;
    }

    @RequestMapping("/registerAdmin")
    @ResponseBody
    public Map<String, Object> registerAdmin(Admin admin, Model model) {
        Map<String, Object> res = new HashMap<>();
        res.put("code", 200);
        res.put("msg", "操作成功");
        boolean b = adminService.save(admin);
        if (!b) {
            res.put("code", -1);
            res.put("msg", "操作失败");
        }
        return res;
    }

    @RequestMapping("/toAddRoom")
    public String toAddRoom(Model model) {
        return "admin/addRoom";
    }

    @RequestMapping("/addRoom")
    @ResponseBody
    public Map<String, Object> addRoom(AdminAddRoomDTO room, Model model) {
        Map<String, Object> res = new HashMap<>();
        res.put("code", 200);
        res.put("msg", "操作成功");
        if (!addRoomCheck(room, res)) {
            return res;
        }
        Classroom classroom = new Classroom();
        BeanUtils.copyProperties(room, classroom);
        String timeRange = room.getTimeRange();
        String[] split = timeRange.split("-");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
        classroom.setOpenTimeStart(LocalTime.parse(split[0].trim(), formatter));
        classroom.setOpenTimeEnd(LocalTime.parse(split[1].trim(), formatter));
        boolean b = classroomService.save(classroom);
        if (!b) {
            res.put("code", -1);
            res.put("msg", "操作失败");
        } else {
            List<Seat> seats = new ArrayList<>();
            for (int i = 1; i <= classroom.getSeatNum(); i++) {
                Seat seat = new Seat();
                seat.setSeatNo(i);
                seat.setClassroomId(classroom.getId());
                seats.add(seat);
            }
           seatService.saveBatch(seats);
        }
        return res;
    }

    @RequestMapping("/editRoom")
    @ResponseBody
    public Map<String, Object> editRoom(AdminAddRoomDTO room, Model model) {
        Map<String, Object> res = new HashMap<>();
        res.put("code", 200);
        res.put("msg", "操作成功");

        Classroom classroom = new Classroom();
        classroom.setId(room.getId());
        classroom.setName(room.getName());
        boolean b = classroomService.updateById(classroom);
        if (!b) {
            res.put("code", -1);
            res.put("msg", "操作失败");
        }
        return res;
    }

    @RequestMapping("/deleteRoom")
    public String deleteRoom(@RequestParam("id") Integer id,Model model) {
        classroomService.removeById(id);
        return "redirect:/room/toRoomList";
    }

    @RequestMapping("/toReservationList")
    public String toReservationList(HttpSession session, Model model) {
        List<SeatOrderVO> list = seatOrderService.getReservationBySno(null, null);
        model.addAttribute("list", list);
        return "admin/reservationList";
    }

    @RequestMapping("/toMyInfo")
    public String toMyInfo(HttpSession session, Model model) {
        Object user = session.getAttribute("loginUser");
        AdminLoginVO loginVO = (AdminLoginVO) user;
        Admin admin = adminService.getById(loginVO.getId());
        model.addAttribute("user", admin);
        return "admin/myInfo";
    }

    @RequestMapping("/updateInfo")
    @ResponseBody
    public Result updateInfo(Admin admin, HttpSession session, Model model) {
        Result vo = new Result(200, "OK");
        adminService.updateById(admin);
        return vo;
    }

    private boolean addRoomCheck(AdminAddRoomDTO room, Map<String, Object> res) {

        Integer seatNum = room.getSeatNum();
        if (seatNum > 50) {
            res.put("code", -1);
            res.put("msg", "座位数最大为50");
            return false;
        }
        String timeRange = room.getTimeRange();
        if (!StringUtils.hasLength(timeRange)) {
            res.put("code", -1);
            res.put("msg", "时间有误");
            return false;
        }

        String[] split = timeRange.split("-");
        if (null == split || split.length != 2) {
            res.put("code", -1);
            res.put("msg", "时间有误");
            return false;
        }

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
        LocalTime s = LocalTime.parse(split[0].trim(), formatter);
        LocalTime e = LocalTime.parse(split[1].trim(), formatter);
        if (s.isAfter(e)) {
            res.put("code", -1);
            res.put("msg", "时间范围有误");
            return false;
        }
        return true;
    }
}
